package model

import (
	"errors"
	"time"
)

type Env struct {
	ID        int    `json:"id" gorm:"primary_key"`
	ProjectId int    `json:"project_id" binding:"required"`
	Host      string `json:"host" binding:"required"`
	Desc      string `json:"desc" binding:"required"`
	IsMaster  byte   `json:"is_master" gorm:"column:is_master" binding:"required"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (*Env) TableName() string {
	return "env"
}

func GetEnvByProjectId(projectId int) []Env {
	var envs []Env
	DBIns.Where("project_id = ?", projectId).Find(&envs)
	return envs
}

func UpdateEnv(id int, env Env) error {
	var currentEnv Env
	var err error
	DBIns.First(&currentEnv, id)
	if currentEnv.ID != 0 {
		currentEnv.Host = env.Host
		currentEnv.Desc = env.Desc
		currentEnv.ProjectId = env.ProjectId
		currentEnv.IsMaster = env.IsMaster
		err = DBIns.Save(&currentEnv).Error
	} else {
		err = errors.New("没有找到该配置")
	}

	return err
}

func AddEnv(env *Env) error {
	return DBIns.Save(env).Error
}
